package club.weiyuanstudio.android.app.message_station.broadcast.message

import android.content.BroadcastReceiver
import android.content.ContentValues.TAG
import android.content.Context
import android.content.Intent
import android.util.Log
import club.weiyuanstudio.android.app.message_station.api.MessageStationAPI
import club.weiyuanstudio.android.app.message_station.ui.setting.SettingViewModel

class MessageBroadcastReceiver : BroadcastReceiver() {
    private val _ACTION = "android.provider.Telephony.SMS_RECEIVED";

    private fun getMessagesFromIntent(intent: Intent): ArrayList<SimpleMessage> {
        val messages: ArrayList<SimpleMessage> = ArrayList()

        val bundle = intent.extras
        if (bundle != null) {
            bundle.keySet().forEach { item ->
                Log.d(TAG, "getMessageFromIntent: " + item + bundle.get(item))
            }

            val pdus = bundle.get("pdus") as Array<*>
            val format = bundle.get("format") as String

            pdus.forEach { item -> messages.add(SimpleMessage(item as ByteArray, format)) }
        }

        return messages
    }

    override fun onReceive(context: Context?, intent: Intent?) {
        val uuid = context?.getSharedPreferences("data", Context.MODE_PRIVATE)?.getString(
            SettingViewModel.SettingType.UUID.name, "UNSET"
        )!!

        if (intent != null) {
            if (_ACTION == intent.action) {
                val messageList = getMessagesFromIntent(intent)

                messageList.forEach { item ->
                    run {
                        val message = item.getMessage()
                        message.nodeUUID = uuid
                        MessageStationAPI().saveMessage(message)
                    }
                }
            }
        }
    }
}
